import { prepareExecute } from '.'

/**
 * 数据库 file 表
 */
// export class FileModel {
//   id?: number
//   fileName?: string 
//   data_buffer?: Buffer
//   name?: string // File字段
//   data?: Buffer // File字段
//   size?: number
//   mimetype?: string // MIMEType
//   md5?: string // dd67f280c5280d7d3c7f719c578ef1ff
// }

export const uploadDao = async (file) => {
  const sql = 'insert into file values (NULL,?,?,?,?,?,CURRENT_TIMESTAMP)'
  const values = [file.name, file.data, file.size, file.mimetype, file.md5]
  return await prepareExecute(sql, values)
}

export const queryFileByMD5Dao = async (md5) => {
  const sql = 'select * from file where md5 = ?'
  return await prepareExecute(sql, [md5])
}

export const deleteFileByMD5Dao = async (md5) => {
  const sql = 'delete from file where md5 = ?'
  return await prepareExecute(sql, [md5])
}

export const uploadMultipleDao = async (files) => {
  const sql = 'insert into file values '
  const sqls = []
  const values = []
  for (let i in files) {
    sqls[i] = '(NULL,?,?,?,?,?,CURRENT_TIMESTAMP)'
    values.push(
      files[i].name,
      files[i].data,
      files[i].size,
      files[i].mimetype,
      files[i].md5,
    )
  }
  const sqlsFinal = sql + sqls.join(',')
  return await prepareExecute(sqlsFinal, values)
}

export const queryFilesByConditonDao = async (condition) => {
  const { keywords, page, pageSize } = condition
  const whereCondition = keywords.trim() ? `file_name like '%${keywords}%'` : '1=1'
  const start = Number(pageSize) * (Number(page) - 1)
  const sql = `select id, file_name, size, mimetype, md5, create_time from file where ${whereCondition} limit ${start}, ${Number(pageSize)}`
  const total = await prepareExecute('select count(*) as total from file', [])
  const list = await prepareExecute(sql, [])
  return {
    page: Number(page), 
    pageSize: Number(pageSize), 
    total: total[0].total, 
    list,
  }
}